package com.lj.graduate.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lj.graduate.common.Constants;
import com.lj.graduate.controller.dto.UserDTO;
import com.lj.graduate.entity.Admin;
import com.lj.graduate.controller.dto.AdminDTO;
import com.lj.graduate.entity.User;
import com.lj.graduate.exception.ServiceException;
import com.lj.graduate.mapper.AdminMapper;
import com.lj.graduate.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lj.graduate.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljy
 * @since 2023-03-23
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    private static final Log LOG = Log.get();
    @Autowired
    private AdminMapper adminMapper;

//    @Override
//    public AdminDTO login(AdminDTO adminDTO) {
//        Admin one = getUserInfo(adminDTO);
//        if (one != null) {
//            BeanUtil.copyProperties(one, adminDTO, true);
//            return adminDTO;
//        } else {
//            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
//        }
//    }
    @Override
    public AdminDTO login(AdminDTO adminDTO) {
        Admin one = getUserInfo(adminDTO);
        if (one != null) {
            BeanUtil.copyProperties(one, adminDTO, true);
            // 设置token
            String token = TokenUtils.genAdminToken(one.getAdministratorId().toString(), one.getAdministratorPassword());
            adminDTO.setToken(token);
            return adminDTO;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }
    }
    private Admin getUserInfo(AdminDTO adminDTO) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("administrator_account", adminDTO.getAdministratorAccount());
        queryWrapper.eq("administrator_password", adminDTO.getAdministratorPassword());
        Admin one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }
}
